'use strict'
import { app, BrowserWindow, ipcMain, Tray, Menu } from 'electron'
import path from 'path'
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let win
let tray = null
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`
const iconPath = path.join(__dirname, '../../build/icons/icon.ico')
function createWindow() {
  win = new BrowserWindow({
    height: 800,
    useContentSize: true,
    width: 1200,
    frame: false,
    resizable: false,
    skipTaskbar: false,
    transparent: false,
    maximizable: false,
    hasShadow: false,
    title: 'HiGame',
    autoHideMenuBar: true,
    icon: iconPath,
    opacity: 0.99,
    webPreferences: {
      webSecurity: false
    }
  })

  win.loadURL(winURL)
  win.setMenu(null)
  win.on('closed', () => {
    win = null
  })

  win.on('show', () => {
    tray.setHighlightMode('always')
  })

  win.on('hide', () => {
    tray.setHighlightMode('never')
  })
  tray = new Tray(iconPath)
  const contextMenu = Menu.buildFromTemplate([
    { label: '退出', click: () => { win.destroy() } }
  ])
  tray.setToolTip('HiGame')
  tray.setContextMenu(contextMenu)
  tray.on('click', () => {
    win.isVisible() ? win.hide() : win.show()
    win.isVisible() ? win.setSkipTaskbar(false) : win.setSkipTaskbar(true)
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (win === null) {
    createWindow()
  }
})

ipcMain.on('hide', e => {
  win.hide()
  win.setSkipTaskbar(true)
  e.preventDefault()
})

ipcMain.on('close', e => {
  win.close()
})

ipcMain.on('minimize', e => {
  win.minimize()
})

let newwin;
ipcMain.on('add', (e,arg) => {
  newwin = new BrowserWindow({
    height: 800,
    useContentSize: true,
    width: 1200,
    frame: true,
    title: 'HiGame',
    autoHideMenuBar: true,
    icon: iconPath,
    parent: win, //win是主窗口
  })
  console.log(arg)
  newwin.loadURL(arg); //new.html是新开窗口的渲染进程
  newwin.on('closed', () => { newwin = null })

})
const shouldQuit = app.makeSingleInstance((commandLine, workingDirectory) => {
  if (win) {
    win.isMinimized() ? win.restore() : null
    !win.isVisible() ? win.show() : null
    win.isVisible() ? win.setSkipTaskbar(false) : null
    win.focus()
  }
})
if (shouldQuit) {
  app.quit()
}
// 获取服务器
